const util = require('../../../../../../../utils/util.js');
const utilTime = require('../../../../../../../utils/time.js');
const api = require('../../../../../../../config/api.js');
const user = require('../../../../../../../services/user.js');
const recorderManager = wx.getRecorderManager();
var recordInterval = null;

//获取应用实例
const app = getApp()
const openid = app.globalData.logininfo.openid;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    seedDialog: { "show": false, "seedRulesDialogShow": false, "diaryInfo": {} },
    energyCardDialog: {"show": false},// 能量卡片
    audioOauhRefusedDialogShow: false,// 语音拒绝授权的弹窗
    circleid: '',// 圈子id
    diaryid: '',// 日记id
    circleInfo: {},//圈子信息
    groupList: [],// 分组信息
    diaryInfo: {},//日记信息
    projectTripCount: {},// 专题行程的喜欢、浏览次数
    diary_givelike_dialog: false,// 点赞成功之后的弹窗
    reviewDialogShow: false,// 控制点评的弹窗显示
    reviewBottomShow: false,// 点评底部的的弹出显示
    reviewImageList: { "imageList": [{ "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }], "totalScore": 0 },// 点评的分数
    reviewTextarea: "",//点评的textarea的值
    reviewTextareaShow: false,// 控制点评的textarea是否显示
    reviewAudio: {},// 点评的音频
    reviewImage: {},// 点评的图片
    quickLanguageShow: false, // 添加快捷语的弹窗显示
    quickLanguageBottomShow: false, // 快捷语底部的的弹出显示
    ordReviewQuickTextLength: 0,// 快捷语的texteare的长度
    ordReviewQuickText: '',// 快捷语的texteare
    ordReviewQuickId: '',// 快捷语的id
    selectReviewQuickIndex: "", //快捷评语选中的下标
    reviewQuickList: [],// 快捷评语数据
    isSubmitAll: false,// 是否正在发布点评
    diary_review_dialog: false,// 点评成功之后的弹窗
    ordReviewId: '',//点评id
    reviewBottomIndex: '',// 点评底部弹出时的日记的index
    reviewBottomEditorAndDeleteIsShow: false, // 点评底部弹出时是否显示编辑和删除
    commonsBottomShow: false,// 评论的底部是否显示
    mainReplyCommentsid: 0,// 评论回复的主id
    replyCommentNickname: '',// 被评论回复的昵称
    replyCommentsid: 0,// 评论回复的id
    isCommonsDelete: false,// 是否显示评论的删除
    diaryCommentsid: '',// 评论的id
    commentsDialogShow: false,//评论的弹窗
    commentsTextarea: '',// 评论的texteare
    commentsAudio: {},// 评论的语音
    diaryOperationShow: false,// 日记操作的底部显示
    updateGroupid: '',// 需要修改的分组id
    groupingDialogShow: false,// 有分组的弹窗
    groupingEmptyDialogShow: false, // 无分组的弹窗
    diaryPrivacyShow: false,// 隐私弹出层
    giveLikeUserDialogShow: false,// 点赞的人弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    var circleid = options.circleid;
    var diaryid = options.diaryid;
    _this.setData({
      circleid: circleid,
      diaryid: diaryid
    })
    _this.updateDiaryPreviewCount();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    // 获取日记信息
    _this.getDiaryInfoByDiaryId();
    // 获取圈子信息
    _this.getCircleDetails();
    // 获取分组信息
    _this.getGroup();
    // 获取用户快捷评语
    _this.getOrdReviewQuick();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var _this = this;
    var id = _this.data.diaryInfo.ordDiary.id;
    var nickname = _this.data.diaryInfo.diaryUserInfo.nickname;
    var imageVideoList = _this.data.diaryInfo.imageVideoList;
    var imageUrl = _this.data.circleInfo.ordInterest.postersIp + _this.data.circleInfo.ordInterest.posterImageUrl;
    for (var i = 0; i < imageVideoList.length; i++) {
      if (imageVideoList[i].imageVideoType == "1"){
        imageUrl = imageVideoList[i].ip + imageVideoList[i].url;
        break;
      }
    }
    return {
      title: nickname + "的日记",
      path: 'pages/home/shareJump/shareJump?id=' + id + "&type=" + util.getShareType("diary") + "&isCheckLogin=1&circleid=" + _this.data.circleid,
      imageUrl: imageUrl
    }
  },

  /**
   * 获取圈子信息
   */
  getCircleDetails: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var data = {};
    data.circleid = circleid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getCircleDetailsQuery(api.Home_GetCircleDetailsApiUrl, data);
      })
    } else {
      _this.getCircleDetailsQuery(api.Home_GetCircleDetailsUrl, data);
    }
  },

  /**
   * 获取圈子信息：请求
   */
  getCircleDetailsQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var circleInfo = res.result.json;
        var circleTitle = circleInfo.ordInterest.title;
        if (circleTitle.length > 10){
          circleTitle = circleTitle.substring(0, 10) + "...";
        }
        circleInfo.ordInterest.circleTitle = circleTitle;
        _this.setData({
          circleInfo: circleInfo
        })
      }
    });
  },

  /**
   * 获取分组信息
   */
  getGroup: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.circleid = circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_GetGroupApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              groupList: res.result.list
            })
          }
        });
      })
    }
  },

  /**
   * 获取快捷语信息
   */
  getOrdReviewQuick: function () {
    var _this = this;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_GetOrdReviewQuickApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              reviewQuickList: res.result.list
            })
          }
        })
      })
    }
  },

  /**
   * 获取单个单个日记详情
   */
  getDiaryInfoByDiaryId: function () {
    var _this = this;
    var data = {};
    data.circleid = _this.data.circleid;
    data.ordDiaryid = _this.data.diaryid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getDiaryInfoByDiaryIdQuery(api.Home_GetDiaryInfoByDiaryIdApiUrl, data);
      })
    } else {
      _this.getDiaryInfoByDiaryIdQuery(api.Home_GetDiaryInfoByDiaryIdUrl, data);
    }
  },

  /**
   * 获取单个日记详情：请求
   */
  getDiaryInfoByDiaryIdQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var json = res.result.json;
        _this.setData({
          diaryInfo: json
        })
        var updateGroupid = _this.data.updateGroupid;
        if (parseInt(updateGroupid) > 0) {
          _this.setData({
            updateGroupid: json.ordInterestJoin.groupid
          })
        }
        _this.getProjectTripCount();
      }
    });
  },

  /**
   * 获取专题行程的喜欢、浏览次数
   */
  getProjectTripCount: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var openid = _this.data.diaryInfo.ordDiary.openid;
    var data = {};
    data.openid = openid;
    data.circleid = circleid;
    util.post(api.Home_GetProjectTripCountUrl, data).then(function (res) {
      if (res.code == 200) {
        _this.setData({
          projectTripCount: res.result.json
        })
      }
    });
  },

  /**
   * 预览图片：日记
   */
  previewImage: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var diaryInfo = _this.data.diaryInfo;
    var imageList = diaryInfo.imageVideoList;
    var urls = [];
    var current = imageList[index].ip + imageList[index].url;
    for (var i = 0; i < imageList.length; i++) {
      if (imageList[i].imageVideoType == "1") {
        urls.push(imageList[i].ip + imageList[i].url);
      }
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  /**
  * 跳转到视频播放页面：日记
  */
  navigateToVideo: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var diaryInfo = _this.data.diaryInfo;
    var diaryid = diaryInfo.ordDiary.id;
    var video = diaryInfo.imageVideoList[index];
    var src = video.ip + video.url;
    wx.navigateTo({
      url: "../../../../../../../pages/home/video/video?state=1&type=2&id=" + diaryid + "&src=" + src
    })
  },

  /**
   * 播放或暂停动作：日记
   */
  voiceBoFang_diary: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var diaryAudioList = _this.data.diaryInfo.diaryAudioList[index];
    var boFangImage = diaryAudioList.boFangImage;
    var ip = diaryAudioList.ip;
    var name = diaryAudioList.name;
    var currentTime = diaryAudioList.currentTime;
    var audiourl = diaryAudioList.url;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (boFangImage == api.AudioBoFangImage_Name) {
      // 切换至暂停状态
      wx.pauseBackgroundAudio();//暂停播放音乐
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["diaryInfo.diaryAudioList[" + index + "].boFangImage"]: api.AudioNoBoFangImage_Name
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();////暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = name;
      backgroundAudioManager.src = ip + audiourl;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["diaryInfo.diaryAudioList[" + index + "].currentTime"]: 0,
          ["diaryInfo.diaryAudioList[" + index + "].startDate"]: "00:00",
          ["diaryInfo.diaryAudioList[" + index + "].boFangImage"]: api.AudioNoBoFangImage_Name
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = parseInt(backgroundAudioManager.currentTime);
        var startDate = util.digitalFormatTime(position);
        _this.setData({
          ["diaryInfo.diaryAudioList[" + index + "].currentTime"]: backgroundAudioManager.currentTime,
          ["diaryInfo.diaryAudioList[" + index + "].startDate"]: startDate
        });
      })
      _this.setData({
        ["diaryInfo.diaryAudioList[" + index + "].boFangImage"]: api.AudioBoFangImage_Name
      });
    }
  },

  /**
   * 播放音乐（滚动条事件）：日记
   */
  voiceSlider_diary: function (e) {
    var _this = this;
    var position = e.detail.value;
    var index = e.currentTarget.dataset.index;
    var diaryAudioList = _this.data.diaryInfo.diaryAudioList[index];
    var boFangImage = diaryAudioList.boFangImage;
    var startDate = util.digitalFormatTime(position);
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (boFangImage == api.AudioBoFangImage_Name) {
      //正在播放状态
      _this.setData({
        ["diaryInfo.diaryAudioList[" + index + "].currentTime"]: position,
        ["diaryInfo.diaryAudioList[" + index + "].boFangImage"]: api.AudioNoBoFangImage_Name
      });
      _this.voiceBoFang_diary(e);
    } else {
      // 未播放状态
      _this.setData({
        ["diaryInfo.diaryAudioList[" + index + "].currentTime"]: position,
        ["diaryInfo.diaryAudioList[" + index + "].startDate"]: startDate
      });
    }
  },

  /**
   * 跳转到公众号展示页面：日记
   */
  navigateToWebView: function (e) {
    var ip = e.currentTarget.dataset.ip;
    var text = e.currentTarget.dataset.text;
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url: '../../../../../../../pages/home/webView/webView?src=' + text,
      })
    } else {
      wx.downloadFile({
        url: ip + text,
        success: function (res) {
          console.log(res);
          var filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
            }
          })
        }
      })
    }
  },

  /**
   * 进入圈子
   */
  navigateToCircleinteraction: function () {
    var _this = this;
    wx.navigateTo({
      url: '../../circleinteraction/circleinteraction?circleid=' + _this.data.circleid
    })
  },

  /**
   * 预览图片：点评
   */
  previewReviewImage: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var xindex = e.currentTarget.dataset.xindex;
    var ordReviewImageList = _this.data.diaryInfo.ordReviewList[index].ordReviewImageList;
    var urls = [];
    var current = ordReviewImageList[xindex].ip + ordReviewImageList[xindex].url;
    for (var i = 0; i < ordReviewImageList.length; i++) {
      urls.push(ordReviewImageList[i].ip + ordReviewImageList[i].url);
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  /**
   * 播放录音：点评详情
   */
  ordReviewBoFang: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var xindex = e.currentTarget.dataset.xindex;
    var ordReviewAudio = _this.data.diaryInfo.ordReviewList[index].ordReviewAudioList[xindex];
    var isBoFang = ordReviewAudio.isBoFang;
    var ip = ordReviewAudio.ip;
    var name = ordReviewAudio.name;
    var currentTime = ordReviewAudio.currentTime;
    var audiourl = ordReviewAudio.url;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      wx.pauseBackgroundAudio();//暂停播放音乐
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["diaryInfo.ordReviewList[" + index + "].ordReviewAudioList[" + xindex + "].isBoFang"]: 0
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = name;
      backgroundAudioManager.src = ip + audiourl;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["diaryInfo.ordReviewList[" + index + "].ordReviewAudioList[" + xindex + "].currentTime"]: 0,
          ["diaryInfo.ordReviewList[" + index + "].ordReviewAudioList[" + xindex + "].isBoFang"]: 0
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = parseInt(backgroundAudioManager.currentTime);
        var startDate = util.digitalFormatTime(position);
        _this.setData({
          ["diaryInfo.ordReviewList[" + index + "].ordReviewAudioList[" + xindex + "].currentTime"]: backgroundAudioManager.currentTime,
          ["diaryInfo.ordReviewList[" + index + "].ordReviewAudioList[" + xindex + "].startDate"]: startDate
        });
      })
      _this.setData({
        ["diaryInfo.ordReviewList[" + index + "].ordReviewAudioList[" + xindex + "].isBoFang"]: 1
      });
    }
  },

  /**
   * 播放录音：评论
   */
  ordCommonsBoFang: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var xindex = e.currentTarget.dataset.xindex;
    var yindex = e.currentTarget.dataset.yindex;
    var ordCommonsAudio = {};
    if (parseInt(yindex) >= 0) {
      ordCommonsAudio = _this.data.diaryInfo.commentsList[index].replyCommentsList[xindex].replyCommentsAudioList[yindex];
    } else {
      ordCommonsAudio = _this.data.diaryInfo.commentsList[index].replyCommentsAudioList[xindex];
    }
    var isBoFang = ordCommonsAudio.isBoFang;
    var ip = ordCommonsAudio.ip;
    var name = ordCommonsAudio.name;
    var currentTime = ordCommonsAudio.currentTime;
    var audiourl = ordCommonsAudio.url;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      wx.pauseBackgroundAudio();//暂停播放音乐
      backgroundAudioManager.pause();//暂停播放音乐
      if (parseInt(yindex) >= 0) {
        _this.setData({
          ["diaryInfo.commentsList[" + index + "].replyCommentsList[" + xindex + "].replyCommentsAudioList[" + yindex + "].isBoFang"]: 0
        });
      } else {
        _this.setData({
          ["diaryInfo.commentsList[" + index + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 0
        });
      }
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();////暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = name;
      backgroundAudioManager.src = ip + audiourl;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        if (parseInt(yindex) >= 0) {
          _this.setData({
            ["diaryInfo.commentsList[" + index + "].replyCommentsList[" + xindex + "].replyCommentsAudioList[" + yindex + "].isBoFang"]: 0,
            ["diaryInfo.commentsList[" + index + "].replyCommentsList[" + xindex + "].replyCommentsAudioList[" + yindex + "].currentTime"]: 0
          });
        } else {
          _this.setData({
            ["diaryInfo.commentsList[" + index + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 0,
            ["diaryInfo.commentsList[" + index + "].replyCommentsAudioList[" + xindex + "].currentTime"]: 0
          });
        }
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        if (parseInt(yindex) >= 0) {
          _this.setData({
            ["diaryInfo.commentsList[" + index + "].replyCommentsList[" + xindex + "].replyCommentsAudioList[" + yindex + "].currentTime"]: backgroundAudioManager.currentTime
          });
        } else {
          _this.setData({
            ["diaryInfo.commentsList[" + index + "].replyCommentsAudioList[" + xindex + "].currentTime"]: backgroundAudioManager.currentTime
          });
        }
      })

      if (parseInt(yindex) >= 0) {
        _this.setData({
          ["diaryInfo.commentsList[" + index + "].replyCommentsList[" + xindex + "].replyCommentsAudioList[" + yindex + "].isBoFang"]: 1
        });
      } else {
        _this.setData({
          ["diaryInfo.commentsList[" + index + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 1
        });
      }
    }
  },

  /**
   * 添加或删除日记能量点赞
   */
  saveOrDeleteOrdDiaryGivelike: function (e) {
    var _this = this;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.diaryid = _this.data.diaryid;
        if (_this.data.diaryInfo.diaryGivelike != null && _this.data.diaryInfo.diaryGivelike.id != null) {
          data.diaryGivelikeid = _this.data.diaryInfo.diaryGivelike.id;
        }
        util.post(api.Home_SaveOrDeleteOrdDiaryGivelikeApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId();
            var energyInfoResults = res.result.energyInfoResults;
            if (energyInfoResults == true) {
              _this.setData({
                diary_givelike_dialog: true
              })
              setTimeout(() => {
                _this.setData({
                  diary_givelike_dialog: false
                })
              }, 2000);
            }
          }
        })
      })
    }
  },

  /**
   * 点评弹窗
   */
  commentsShow: function (e) {
    var _this = this;
    _this.setData({
      reviewBottomShow: false,
      reviewDialogShow: true
    })
  },

  /**
   * 点评的星星点击事件
   */
  reviewScoreTap: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var imageList = _this.data.reviewImageList.imageList;
    var clickNumber = imageList[index].clickNumber;
    for (var i = 0; i < imageList.length; i++) {
      imageList[i].clickNumber = 0;
    }
    for (var i = 0; i < index; i++) {
      imageList[i].clickNumber = 2;
    }
    if (clickNumber < 2) {
      imageList[index].clickNumber = clickNumber + 1;
    } else {
      imageList[index].clickNumber = 0;
    }
    var totalClickNumber = 0;
    for (var i = 0; i < imageList.length; i++) {
      totalClickNumber = totalClickNumber + imageList[i].clickNumber;
    }
    var reviewImageList = { "imageList": imageList, "totalScore": totalClickNumber };
    _this.setData({
      reviewImageList: reviewImageList
    })
  },

  /**
   * 点评的textarea的焦点移入事件
   */
  reviewTextareaCheckYes: function (e) {
    var _this = this;
    var reviewTextareaShow = _this.data.reviewTextareaShow;
    _this.setData({
      reviewTextareaShow: true
    })
  },

  /**
   * 点评的textarea的焦点移出事件
   */
  reviewTextareaCheckNo: function (e) {
    var _this = this;
    var reviewTextareaShow = _this.data.reviewTextareaShow;
    _this.setData({
      reviewTextareaShow: false
    })
  },

  /**
   * 点评的texteare的输入事件
   */
  reviewTextareaInput: function (e) {
    var _this = this;
    var reviewTextarea = e.detail.value;
    _this.setData({
      reviewTextarea: reviewTextarea
    })
  },

  /**
   * 点评录音
   */
  reviewAudioTap: function () {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          // 未授权
          wx.authorize({
            scope: 'scope.record',
            success() {
              _this.reviewAudioStart();
            },
            fail: function () {
              // 拒绝授权
              _this.setData({
                audioOauhRefusedDialogShow: true
              })
            }
          })
        } else {
          // 已授权
          _this.reviewAudioStart();
        }
      }
    })
  },

  /**
   * 开始录音：点评
   */
  reviewAudioStart: function () {
    var _this = this;
    var reviewAudio = {};
    reviewAudio.isupload = true;
    reviewAudio.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    reviewAudio.playState = "1";// 1正常录音  2暂停录音
    reviewAudio.isBoFang = "0";
    reviewAudio.totalTime = 0;
    reviewAudio.totalDate = "00:00";
    reviewAudio.isVoiceDialogShow = true;
    _this.setData({
      reviewAudio: reviewAudio
    })

    const recorderOptions = {
      duration: util.getAudioFileMaxTime("diaryReview"),//指定录音的时长，单位 ms，默认十分钟
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(recorderOptions);

    // 定时器计算录音时间
    _this.doReviewRecordInterval();

    // 录音结束
    recorderManager.onStop((res) => {
      _this.reviewStopRecorderExecute(res);
    });

    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.reviewStopRecorderExecute(res);
    });
  },

  /**
   * 播放或暂停动作
   */
  reviewAudioBoFang: function (e) {
    var _this = this;
    var src = _this.data.reviewAudio.src;
    var title = _this.data.reviewAudio.title;
    var currentTime = _this.data.reviewAudio.currenttime;
    var isBoFang = _this.data.reviewAudio.isBoFang;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["reviewAudio.isBoFang"]: "0"
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = src;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["reviewAudio.currentTime"]: 0,
          ["reviewAudio.isBoFang"]: "0",
          ["reviewAudio.startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["reviewAudio.currentTime"]: backgroundAudioManager.currentTime,
          ["reviewAudio.startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["reviewAudio.isBoFang"]: "1"
      });
    }
  },

  /**
   * 清除定时器
   */
  doClearInterval: function () {
    clearInterval(recordInterval);
    recordInterval = null;
  },

  /**
   * 定时器计算录音时间
   */
  doReviewRecordInterval: function () {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var reviewAudio = _this.data.reviewAudio;
        var totalTime = reviewAudio.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["reviewAudio.totalTime"]: totalTime,
          ["reviewAudio.totalDate"]: totalDate
        });
      }, 1000);
    }
  },

  /**
   * 停止录音后的业务代码：点评
   */
  reviewStopRecorderExecute: function (tempFile) {
    var _this = this;
    _this.doClearInterval();
    var isVoiceDialogShow = _this.data.reviewAudio.isVoiceDialogShow;
    if (isVoiceDialogShow) {
      var totalTime = parseInt(tempFile.duration / 1000);
      var reviewAudio = _this.data.reviewAudio;
      reviewAudio.state = "2";
      reviewAudio.src = tempFile.tempFilePath;
      reviewAudio.title = "录音音频";
      reviewAudio.currentTime = 0;
      reviewAudio.totalTime = totalTime;
      reviewAudio.fileSize = tempFile.fileSize;
      reviewAudio.startDate = "00:00";
      reviewAudio.totalDate = util.digitalFormatTime(totalTime);
      reviewAudio.isBoFang = "0";
      _this.setData({
        reviewAudio: reviewAudio
      })
    } else {
      /*_this.setData({
        reviewAudio: {}
      })*/
    }
  },

  /**
   * 暂停录音：点评
   */
  reviewPauseRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["reviewAudio.playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },

  /**
   * 继续录音：点评
   */
  reviewResumeRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["reviewAudio.playState"]: "1"
    })
    recorderManager.resume();
    _this.doReviewRecordInterval();
  },

  /**
   * 停止录音：点评
   */
  reviewStopRecorder: function (e) {
    var _this = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.reviewStopRecorderExecute(res);
    });
  },

  /**
   * 清空录音：点评
   */
  clearReviewRecorder: function () {
    var _this = this;
    _this.setData({
      ["reviewAudio.isVoiceDialogShow"]: false
    })
    _this.doClearInterval();
    recorderManager.stop();

    setTimeout(function () {
      _this.reviewAudioTap();
    }, 100)
  },

  /**
   * 删除录音：点评
   */
  deleteReviewRecorder: function () {
    var _this = this;
    _this.doClearInterval();
    recorderManager.stop();
    var isupload = _this.data.reviewAudio.isupload;
    var reviewAudio = {};
    reviewAudio.isupload = isupload;
    if (!isupload) {
      // 删除的是已存数据库的
      reviewAudio.isDelete = true;
    }
    _this.setData({
      reviewAudio: reviewAudio
    })
  },

  /**
   * 点评图片
   */
  reviewImageTap: function () {
    var _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var reviewImage = {};
        reviewImage = res.tempFiles[0];
        reviewImage.isupload = true;
        _this.setData({
          reviewImage: reviewImage
        })
      }
    })
  },

  /**
   * 删除点评图片
   */
  deleteReviewImage: function () {
    var _this = this;
    var isupload = _this.data.reviewImage.isupload;
    console.log(_this.data.reviewImage)
    var reviewImage = {};
    reviewImage.isupload = isupload;
    if (!isupload) {
      // 删除的是已存数据库的
      reviewImage.isDelete = true;
    }
    _this.setData({
      reviewImage: reviewImage
    })
  },

  /**
   * 添加快捷语弹窗的显示
   */
  quickLanguageShow: function () {
    var _this = this;
    var quickLanguageShow = _this.data.quickLanguageShow;
    _this.setData({
      quickLanguageShow: true
    })
  },

  /**
   * 添加快捷语弹窗的显示：编辑
   */
  quickLanguageShow2: function () {
    var _this = this;
    var quickLanguageShow = _this.data.quickLanguageShow;
    var index = _this.data.selectReviewQuickIndex;
    var ordReviewQuickId = _this.data.reviewQuickList[index].id;
    var ordReviewQuickText = _this.data.reviewQuickList[index].text;
    _this.setData({
      quickLanguageBottomShow: false,
      quickLanguageShow: true,
      ordReviewQuickText: ordReviewQuickText,
      ordReviewQuickTextLength: ordReviewQuickText.length,
      ordReviewQuickId: ordReviewQuickId,
      selectReviewQuickIndex: ''
    })
  },

  /**
  * 添加快捷语弹窗的隐藏
  */
  quickLanguageBottomClose: function () {
    var _this = this;
    _this.setData({
      quickLanguageBottomShow: false,
      selectReviewQuickIndex: '',
      ordReviewQuickId: ''
    })
  },

  /**
   * 快捷语置顶
   */
  quickLanguagePlacedTop: function () {
    var _this = this;
    var index = _this.data.selectReviewQuickIndex;
    var ordReviewQuickId = _this.data.reviewQuickList[index].id;
    var isPlacedtop = _this.data.reviewQuickList[index].isPlacedtop;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.ordReviewQuickId = ordReviewQuickId;
        data.isPlacedtop = isPlacedtop == 0 ? "1" : "0";
        data.access_token = res.access_token;
        util.post(api.Home_SaveOrUpdateReviewQuickApiUrl, data).then(function (res) {
          _this.getOrdReviewQuick();
          _this.quickLanguageBottomClose();
        })
      })
    }
  },

  /**
   * 删除快捷语
   */
  deleteOrdReviewQuick: function () {
    var _this = this;
    var index = _this.data.selectReviewQuickIndex;
    var ordReviewQuickId = _this.data.reviewQuickList[index].id;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.ordReviewQuickId = ordReviewQuickId;
        data.access_token = res.access_token;
        util.post(api.Home_DeleteOrdReviewQuickApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              quickLanguageBottomShow: false,
              selectReviewQuickIndex: ''
            })
            _this.getOrdReviewQuick();
          }
        })
      })
    }
  },

  /**
   * 添加快捷语弹窗的关闭
   */
  quickLanguageClose: function () {
    var _this = this;
    var quickLanguageShow = _this.data.quickLanguageShow;
    _this.setData({
      quickLanguageShow: false,
      ordReviewQuickText: '',
      ordReviewQuickId: '',
      selectReviewQuickIndex: '',
      ordReviewQuickTextLength: 0
    })
  },

  /**
   * 获取快捷语信息
   */
  getOrdReviewQuick: function () {
    var _this = this;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_GetOrdReviewQuickApiUrl, data).then(function (res) {
          if (res.code == 200) {
            var reviewQuickList = res.result.list;
            _this.setData({
              reviewQuickList: reviewQuickList
            })
          }
        })
      })
    }
  },

  /**
   * 快捷语的list右侧的点点点选中事件
   */
  selectReviewQuick: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      selectReviewQuickIndex: index,
      quickLanguageBottomShow: true
    })
  },

  /**
   * 快捷语的textarea输入事件
   */
  ordReviewQuickTextInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    _this.setData({
      ordReviewQuickText: value,
      ordReviewQuickTextLength: value.length
    })
  },

  /**
   * 快捷评语选中事件
   */
  reviewQuickCenterTap: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var text = _this.data.reviewQuickList[index].text;
    var reviewTextarea = _this.data.reviewTextarea;
    if (reviewTextarea.length > 0) {
      text = reviewTextarea + "，" + text;
    }
    _this.setData({
      reviewTextarea: text
    })
  },

  /**
   * 快捷语的list右侧的点点点选中事件
   */
  selectReviewQuick: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      selectReviewQuickIndex: index,
      quickLanguageBottomShow: true
    })
  },

  /**
   * 保存或者删除评语
   */
  saveOrUpdateReviewQuick: function () {
    var _this = this;
    var ordReviewQuickId = _this.data.ordReviewQuickId;
    var ordReviewQuickText = _this.data.ordReviewQuickText;
    if (openid != null && openid != "" && ordReviewQuickText.length > 0) {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.ordReviewQuickId = ordReviewQuickId;
        data.ordReviewQuickText = ordReviewQuickText;
        data.access_token = res.access_token;
        util.post(api.Home_SaveOrUpdateReviewQuickApiUrl, data).then(function (res) {
          _this.getOrdReviewQuick();
          _this.quickLanguageClose();
        })
      })
    }
  },

  /**
     * 取消点评
     */
  closeReview: function () {
    var _this = this;
    _this.deleteCommentsRecorder();
    _this.setData({
      reviewBottomIndex: '',
      reviewDialogShow: false,
      reviewImageList: { "imageList": [{ "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }], "totalScore": 0 },
      reviewTextarea: '',
      reviewAudio: {},
      reviewImage: {},
    })
  },

  /**
   * 发表点评
   */
  submitReview: function () {
    var _this = this;
    var totalScore = _this.data.reviewImageList.totalScore;
    var reviewTextarea = _this.data.reviewTextarea;
    var reviewAudio = _this.data.reviewAudio;
    var reviewImage = _this.data.reviewImage;
    if (!(reviewTextarea.length > 0 || (reviewAudio.state != null && reviewAudio.state.length > 0) || (reviewImage.path != null && reviewImage.path.length > 0))) {
      util.dialogAlert("评论内容不能为空");
      return false;
    } else if (reviewAudio.state != null && reviewAudio.state == "1") {
      util.dialogAlert("正在录制音频中");
      return false;
    }
    wx.showLoading({
      title: '保存中',
    })
    _this.setData({
      isSubmitAll: false
    })
    var uploadInfoList = [];
    if (reviewImage.path != null && reviewImage.path.length > 0 && reviewImage.isupload) {
      var uploadInfo = {};
      uploadInfo.type = "1";// 类型:1图片  2音频  3视频
      uploadInfo.filePath = reviewImage.path;
      uploadInfoList.push(uploadInfo);
    }
    if (reviewAudio.state != null && reviewAudio.state == "2" && reviewAudio.isupload) {
      var uploadInfo = {};
      uploadInfo.type = "2";// 类型:1图片  2音频  3视频
      uploadInfo.filePath = reviewAudio.src;
      uploadInfoList.push(uploadInfo);
    }
    if (uploadInfoList.length > 0) {
      // 开始请求:要先上传
      _this.uploadFileQuery(uploadInfoList, 0);
    } else {
      _this.saveReview();
    }
  },

  /**
   * 上传
   */
  uploadFileQuery: function (data, queryIndex) {
    var _this = this;
    var queryData = data[queryIndex];
    var queryUrl = "";
    switch (queryData.type) {
      case "1":
        // 图片
        queryUrl = api.File_doImageUpload;
        break;
      case "2":
        // 音频
        queryUrl = api.File_doAudioUpload;
        break;
    }
    wx.uploadFile({
      url: queryUrl,
      filePath: queryData.filePath,
      name: 'file',
      formData: {
        "type": "4"
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          var ip = data.result.ip;
          var path = data.result.path;
          switch (queryData.type) {
            case "1":
              // 图片
              _this.setData({
                ["reviewImage.ip"]: ip,
                ["reviewImage.path"]: path
              })
              break;
            case "2":
              // 音频
              _this.setData({
                ["reviewAudio.ip"]: ip,
                ["reviewAudio.src"]: path
              })
              break;
          }
        }
      },
      fail(res) {
        // 失败
      },
      complete(res) {
        // 结束：
        if (queryIndex < data.length - 1) {
          // 图片未上传完成，继续上传
          queryIndex++;
          _this.uploadFileQuery(data, queryIndex);
        } else {
          // 上传完成，执行save请求
          _this.saveReview();
        }
      }
    })
  },

  /**
   * save点评请求
   */
  saveReview: function () {
    var _this = this;
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.openid = openid;
      data.access_token = res.access_token;
      data.circleid = _this.data.circleid;
      data.ordDiaryid = _this.data.diaryid;
      data.ordReviewScore = _this.data.reviewImageList.totalScore;
      data.ordReviewText = _this.data.reviewTextarea;
      data.ordReviewId = _this.data.ordReviewId;
      if (_this.data.reviewAudio.isupload || _this.data.reviewAudio.isDelete) {
        data.ordReviewAudio = JSON.stringify(_this.data.reviewAudio);
      } else {
        data.ordReviewAudio = "";
      }
      if (_this.data.reviewImage.isupload || _this.data.reviewImage.isDelete) {
        data.ordReviewImage = JSON.stringify(_this.data.reviewImage);
      } else {
        data.ordReviewImage = "";
      }
      util.post(api.Home_SaveOrUpdateOrdReviewApiUrl, data).then(function (res) {
        wx.hideLoading();
        _this.setData({
          isSubmitAll: false
        })
        if (res.code == 200) {
          _this.getDiaryInfoByDiaryId();
          _this.closeReview();
          var energyInfoResults = res.result.energyInfoResults;
          if (energyInfoResults == true) {
            _this.setData({
              diary_review_dialog: true
            })
            setTimeout(() => {
              _this.setData({
                diary_review_dialog: false
              })
            }, 2000);
          }
        }
      })
    })
  },

  /**
     * 点评底部的的弹出显示
     */
  reviewBottomShow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var ordReviewOpenid = _this.data.diaryInfo.ordReviewList[index].ordReview.openid;
    var thisInterestJoinUser = _this.data.circleInfo.thisInterestJoinUser;
    var reviewBottomEditorAndDeleteIsShow = false;
    if (thisInterestJoinUser.identitytype == 1 || thisInterestJoinUser.identitytype == 2 || thisInterestJoinUser.identitytype == 3) {
      reviewBottomEditorAndDeleteIsShow = true;
    }
    if (ordReviewOpenid == openid) {
      reviewBottomEditorAndDeleteIsShow = true;
    }
    _this.setData({
      reviewBottomShow: true,
      reviewBottomIndex: index,
      reviewBottomEditorAndDeleteIsShow: reviewBottomEditorAndDeleteIsShow
    })
  },

  /**
   * 点评底部的的弹出关闭
   */
  reviewBottomClose: function (e) {
    var _this = this;
    _this.setData({
      reviewBottomShow: false,
      reviewBottomIndex: '',
      reviewBottomEditorAndDeleteIsShow: false
    })
  },

  /**
   * 编辑新点评
   */
  reviewBottomEditor: function (e) {
    var _this = this;
    var imageList = _this.data.reviewImageList.imageList;
    var index = _this.data.reviewBottomIndex;
    var reviewBottomInfo = _this.data.diaryInfo.ordReviewList[index];
    var ordReview = reviewBottomInfo.ordReview;
    var ordReviewAudioList = reviewBottomInfo.ordReviewAudioList;
    var ordReviewImageList = reviewBottomInfo.ordReviewImageList;
    var score = ordReview.score;
    var ordReviewId = ordReview.id;
    var reviewTextarea = ordReview.text;
    var scoreIndex = 0;
    var dyScore = 0;
    if (score > 0) {
      if (score % 2 == 0) {
        scoreIndex = score / 2;
      } else {
        dyScore = 1;
        scoreIndex = (score - 1) / 2;
      }
    }
    for (var i = 0; i < imageList.length; i++) {
      imageList[i].clickNumber = 0;
    }
    for (var i = 0; i < scoreIndex; i++) {
      imageList[i].clickNumber = 2;
    }
    if (dyScore > 0) {
      imageList[scoreIndex].clickNumber = 1;
    }
    var reviewImageList = { "imageList": imageList, "totalScore": score };
    var reviewAudio = {};
    var reviewImage = {};
    if (ordReviewAudioList.length > 0) {
      var ordReviewAudio = ordReviewAudioList[0];
      reviewAudio.currentTime = 0;
      reviewAudio.isBoFang = 0;
      reviewAudio.isVoiceDialogShow = true;
      reviewAudio.isupload = false;
      reviewAudio.playState = "1";
      reviewAudio.src = ordReviewAudio.ip + ordReviewAudio.url;
      reviewAudio.startDate = "00:00";
      reviewAudio.state = "2";
      reviewAudio.title = ordReviewAudio.name;
      reviewAudio.totalDate = ordReviewAudio.totalDate;
      reviewAudio.totalTime = ordReviewAudio.totalTime;
    }
    if (ordReviewImageList.length > 0) {
      var ordReviewImage = ordReviewImageList[0];
      reviewImage.path = ordReviewImage.ip + ordReviewImage.url;
      reviewImage.isupload = false;
    }
    _this.setData({
      reviewImageList: reviewImageList,
      reviewBottomShow: false,
      reviewDialogShow: true,
      reviewTextarea: reviewTextarea,
      reviewAudio: reviewAudio,
      reviewImage: reviewImage,
      ordReviewId: ordReviewId
    })
  },

  /**
   * 删除点评弹窗
   */
  reviewBottomDelete: function () {
    var _this = this;
    _this.setData({
      reviewBottomShow: false,
      reviewBottomDeleteShow: true
    })
  },

  /**
   * 删除点评取消
   */
  reviewBottomDeleteClose: function () {
    var _this = this;
    _this.setData({
      reviewBottomIndex: '',
      reviewBottomDeleteShow: false
    })
  },

  /**
   * 删除点评确定
   */
  reviewBottomDeleteSuccess: function () {
    var _this = this;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var index = _this.data.reviewBottomIndex;
        var ordReviewId = _this.data.diaryInfo.ordReviewList[index].ordReview.id;
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.ordDiaryid = _this.data.diaryid;
        data.ordReviewId = ordReviewId;
        util.post(api.Home_DeleteOrdReviewApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              reviewBottomIndex: '',
              reviewBottomDeleteShow: false
            })
            _this.getDiaryInfoByDiaryId();
          }
        })
      })
    }
  },

  /**
   * 评论的右侧点击显示底部的弹窗
   */
  commonsBottomShow: function (e) {
    var _this = this;
    var id = e.currentTarget.dataset.id;
    var mainid = e.currentTarget.dataset.mainid;
    var nickname = e.currentTarget.dataset.nickname;
    var commonsopenid = e.currentTarget.dataset.commonsopenid;
    var diaryCommentsid = e.currentTarget.dataset.deleteid;
    var thisInterestJoinUser = _this.data.circleInfo.thisInterestJoinUser;
    var isCommonsDelete = false;
    if (thisInterestJoinUser.identitytype == 1 || thisInterestJoinUser.identitytype == 2 || thisInterestJoinUser.identitytype == 3) {
      isCommonsDelete = true;
    }
    if (commonsopenid == openid) {
      isCommonsDelete = true;
    }
    _this.setData({
      commonsBottomShow: true,
      replyCommentsid: id,
      mainReplyCommentsid: mainid,
      replyCommentNickname: nickname,
      isCommonsDelete: isCommonsDelete,
      diaryCommentsid: diaryCommentsid
    })
  },

  /**
   * 评论的右侧点击关闭底部的弹窗
   */
  commonsBottomClose: function () {
    var _this = this;
    _this.setData({
      commonsBottomShow: false,
      replyCommentsid: 0,
      mainReplyCommentsid: 0,
      replyCommentNickname: ''
    })
  },

  /**
   * 删除评论
   */
  commentsDelete: function () {
    var _this = this;
    var replyCommentsid = _this.data.replyCommentsid;
    if (openid != null && openid != "") {
      wx.showLoading({
        title: "删除中"
      })
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.diaryid = _this.data.diaryid;
        data.diaryCommentsid = _this.data.diaryCommentsid;
        util.post(api.Home_DeleteOrdDiaryCommentsApiUrl, data).then(function (res) {
          wx.hideLoading();
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId();
            _this.commonsBottomClose();
          }
        });
      })
    }
  },

  /**
   * 评论的弹窗打开
   */
  commentsDialogShow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      commentsDialogShow: true,
      commonsBottomShow: false
    })
  },

  /**
   * 评论的弹窗关闭
   */
  commentsDialogClose: function () {
    var _this = this;
    _this.deleteCommentsRecorder();
    _this.setData({
      commentsTextarea: '',
      commentsAudio: {},
      commentsDialogShow: false,
      replyCommentsid: 0,
      mainReplyCommentsid: 0,
      replyCommentNickname: ''
    })
  },

  /**
   * 评论的texteare的输入事件
   */
  commentsTextareaInput: function (e) {
    var _this = this;
    var commentsTextarea = e.detail.value;
    _this.setData({
      commentsTextarea: commentsTextarea
    })
  },

  /**
  * 评论录音
  */
  commentsAudioTap: function () {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          // 未授权
          wx.authorize({
            scope: 'scope.record',
            success() {
              _this.commentsAudioStart();
            },
            fail: function () {
              // 拒绝授权
              _this.setData({
                audioOauhRefusedDialogShow: true
              })
            }
          })
        } else {
          // 已授权
          _this.commentsAudioStart();
        }
      }
    })
  },

  /**
   * 开始录音：评论
   */
  commentsAudioStart: function () {
    var _this = this;
    var commentsAudio = {};
    commentsAudio.isupload = true;
    commentsAudio.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    commentsAudio.playState = "1";// 1正常录音  2暂停录音
    commentsAudio.isBoFang = "0";
    commentsAudio.totalTime = 0;
    commentsAudio.totalDate = "00:00";
    commentsAudio.isVoiceDialogShow = true;
    _this.setData({
      commentsAudio: commentsAudio
    })

    const recorderOptions = {
      duration: util.getAudioFileMaxTime("diaryComments"),//指定录音的时长，单位 ms，默认十分钟
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(recorderOptions);

    // 定时器计算录音时间
    _this.doCommentsRecordInterval();

    // 录音结束
    recorderManager.onStop((res) => {
      _this.commentsStopRecorderExecute(res);
    });

    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.commentsStopRecorderExecute(res);
    });
  },

  /**
   * 停止录音后的业务代码：评论
   */
  commentsStopRecorderExecute: function (tempFile) {
    var _this = this;
    _this.doClearInterval();
    var isVoiceDialogShow = _this.data.commentsAudio.isVoiceDialogShow;
    if (isVoiceDialogShow) {
      var totalTime = parseInt(tempFile.duration / 1000);
      var commentsAudio = _this.data.commentsAudio;
      commentsAudio.state = "2";
      commentsAudio.src = tempFile.tempFilePath;
      commentsAudio.title = "录音音频";
      commentsAudio.currentTime = 0;
      commentsAudio.totalTime = totalTime;
      commentsAudio.fileSize = tempFile.fileSize;
      commentsAudio.startDate = "00:00";
      commentsAudio.totalDate = util.digitalFormatTime(totalTime);
      commentsAudio.isBoFang = "0";
      _this.setData({
        commentsAudio: commentsAudio
      })
    } else {
      /*_this.setData({
        commentsAudio: {}
      })*/
    }
  },

  /**
   * 定时器计算录音时间：评论
   */
  doCommentsRecordInterval: function () {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var commentsAudio = _this.data.commentsAudio;
        var totalTime = commentsAudio.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["commentsAudio.totalTime"]: totalTime,
          ["commentsAudio.totalDate"]: totalDate
        });
      }, 1000);
    }
  },

  /**
   * 暂停录音：评论
   */
  commentsPauseRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["commentsAudio.playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },

  /**
   * 继续录音：评论
   */
  commentsResumeRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["commentsAudio.playState"]: "1"
    })
    recorderManager.resume();
    _this.doCommentsRecordInterval();
  },

  /**
   * 停止录音：评论
   */
  commentsStopRecorder: function (e) {
    var _this = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.commentsStopRecorderExecute(res);
    });
  },

  /**
   * 删除录音：评论
   */
  deleteCommentsRecorder: function () {
    var _this = this;
    _this.setData({
      ["commentsAudio.isVoiceDialogShow"]: false,
      commentsAudio: {}
    })
    _this.doClearInterval();
    recorderManager.stop();
  },

  /**
   * 清空录音：评论
   */
  clearCommentsRecorder: function () {
    var _this = this;
    _this.setData({
      ["commentsAudio.isVoiceDialogShow"]: false
    })
    _this.doClearInterval();
    recorderManager.stop();

    setTimeout(function () {
      _this.commentsAudioTap();
    }, 100)
  },

  /**
   * 播放或暂停动作
   */
  commentsAudioBoFang: function (e) {
    var _this = this;
    var src = _this.data.commentsAudio.src;
    var title = _this.data.commentsAudio.title;
    var currentTime = _this.data.commentsAudio.currenttime;
    var isBoFang = _this.data.commentsAudio.isBoFang;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["commentsAudio.isBoFang"]: "0"
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = src;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["commentsAudio.currentTime"]: 0,
          ["commentsAudio.isBoFang"]: "0",
          ["commentsAudio.startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["commentsAudio.currentTime"]: backgroundAudioManager.currentTime,
          ["commentsAudio.startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["commentsAudio.isBoFang"]: "1"
      });
    }
  },

  /**
  * 发表评论
  */
  submitComments: function () {
    var _this = this;
    var commentsTextarea = _this.data.commentsTextarea;
    var commentsAudio = _this.data.commentsAudio;
    if (!(commentsTextarea.length > 0 || (commentsAudio.state != null && commentsAudio.state.length > 0))) {
      util.dialogAlert("评论内容不能为空");
      return false;
    } else if (commentsAudio.state != null && commentsAudio.state == "1") {
      util.dialogAlert("正在录制音频中");
      return false;
    }
    wx.showLoading({
      title: '保存中',
    })
    _this.setData({
      isSubmitAll: false
    })
    var uploadInfoList = [];
    if (commentsAudio.state != null && commentsAudio.state == "2" && commentsAudio.isupload) {
      var uploadInfo = {};
      uploadInfo.type = "2";// 类型:1图片  2音频  3视频
      uploadInfo.filePath = commentsAudio.src;
      uploadInfoList.push(uploadInfo);
    }
    if (uploadInfoList.length > 0) {
      // 开始请求:要先上传
      _this.uploadCommentsFileQuery(uploadInfoList, 0);
    } else {
      _this.saveComments();
    }
  },

  /**
   * 上传评论
   */
  uploadCommentsFileQuery: function (data, queryIndex) {
    var _this = this;
    var queryData = data[queryIndex];
    var queryUrl = "";
    switch (queryData.type) {
      case "2":
        // 音频
        queryUrl = api.File_doAudioUpload;
        break;
    }
    wx.uploadFile({
      url: queryUrl,
      filePath: queryData.filePath,
      name: 'file',
      formData: {
        "type": "5"
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          var ip = data.result.ip;
          var path = data.result.path;
          switch (queryData.type) {
            case "2":
              // 音频
              _this.setData({
                ["commentsAudio.ip"]: ip,
                ["commentsAudio.src"]: path
              })
              break;
          }
        }
      },
      fail(res) {
        // 失败
      },
      complete(res) {
        // 结束：
        if (queryIndex < data.length - 1) {
          // 图片未上传完成，继续上传
          queryIndex++;
          _this.uploadFileQuery(data, queryIndex);
        } else {
          // 上传完成，执行save请求
          _this.saveComments();
        }
      }
    })
  },

  /**
   * save评论请求
   */
  saveComments: function () {
    var _this = this;
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.openid = openid;
      data.access_token = res.access_token;
      data.circleid = _this.data.circleid;
      data.diaryid = _this.data.diaryid;
      data.replyCommentsid = _this.data.replyCommentsid;
      data.mainReplyCommentsid = _this.data.mainReplyCommentsid;
      data.diaryText = _this.data.commentsTextarea;
      if (_this.data.commentsAudio.state != null && _this.data.commentsAudio.state == "2") {
        data.diaryAudio = JSON.stringify(_this.data.commentsAudio);
      }
      util.post(api.Home_SaveOrUpdateOrdDiaryCommentsApiUrl, data).then(function (res) {
        wx.hideLoading();
        _this.setData({
          isSubmitAll: false
        })
        if (res.code == 200) {
          _this.getDiaryInfoByDiaryId();
          _this.commentsDialogClose();
          var energyInfoResults = res.result.energyInfoResults;
          if (energyInfoResults == true) {
            _this.setData({
              diary_commones_dialog: true
            })
            setTimeout(() => {
              _this.setData({
                diary_commones_dialog: false
              })
            }, 2000);
          }
        }
      })
    })
  },

  /**
   * 添加或删除日记评论的点赞
   */
  saveOrDeleteOrdDiaryCommentsGivelike: function (e) {
    var _this = this;
    var commentsid = e.currentTarget.dataset.commentsid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.diaryid = _this.data.diaryid;
        data.diaryCommentsid = commentsid;
        util.post(api.Home_SaveOrDeleteOrdDiaryCommentsGivelikeApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId();
          }
        })
      })
    }
  },

  /**
   * 日记操作的底部展示弹窗
   */
  diaryOperationShow: function (e) {
    var _this = this;
    _this.setData({
      diaryOperationShow: true
    })
  },

  /**
   * 置顶加精或者取消加精
   */
  updateDiaryPlacedtop: function () {
    var _this = this;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var ordDiaryid = _this.data.diaryid;
        var circleid = _this.data.circleid;
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = circleid;
        data.ordDiaryid = ordDiaryid;
        util.post(api.Home_UpdateDiaryPlacedtopApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              ["ordDiary.isPlacedtop"]: res.result.count
            })
            _this.getDiaryInfoByDiaryId();
            _this.diaryOperationClose();
          }
        })
      })
    }
  },

  /**
   * 日记操作的底部关闭弹窗
   */
  diaryOperationClose: function () {
    var _this = this;
    _this.setData({
      updateGroupid: "",
      groupingDialogShow: false,
      diaryOperationShow: false
    })
  },

  /**
   * 设置分组
   */
  setUpGroup: function () {
    var _this = this;
    var groupList = _this.data.groupList;
    var updateGroupid = _this.data.diaryInfo.ordInterestJoin.groupid;
    if (groupList.length > 0) {
      // 有分组，展示分组
      _this.setData({
        diaryOperationShow: false,
        groupingDialogShow: true,
        updateGroupid: updateGroupid
      })
    } else {
      // 无分组
      _this.diaryOperationClose();
      _this.setData({
        groupingEmptyDialogShow: true
      })
    }
  },

  /**
   * 无分组弹窗关闭
   */
  groupingEmptyDialogClose: function () {
    var _this = this;
    _this.setData({
      groupingEmptyDialogShow: false
    })
  },

  /**
   * 无分组弹窗确定
   */
  groupingEmptyDialogConfirm: function () {
    var _this = this;
    _this.setData({
      groupingEmptyDialogShow: false
    })
    _this.navigateToGroup();
  },

  /**
   * 跳转到分组的页面
   */
  navigateToGroup: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    wx.navigateTo({
      url: '../../circleinteraction/group/group?circleid=' + circleid,
    })
  },

  /**
   * 设置分组提交
   */
  groupingDialogConfirm: function () {
    var _this = this;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var updateGroupid = _this.data.updateGroupid;
        var joinid = _this.data.diaryInfo.ordInterestJoin.joinid;
        var data = {};
        data.joinid = joinid;
        data.groupid = updateGroupid;
        data.circleid = _this.data.circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_UpdateJoinUserInfoApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId();
            _this.diaryOperationClose();
            _this.getGroup();
          }
        })
      })
    }
  },

  /**
   * 成员设置分组选中事件
   */
  groupListBindTap: function (e) {
    var _this = this;
    var updateGroupid = e.currentTarget.dataset.id;
    _this.setData({
      updateGroupid: updateGroupid
    })
  },

  /**
   * 设置日记隐私
   */
  diaryPrivacyShow: function () {
    var _this = this;
    _this.setData({
      diaryPrivacyShow: true
    })
    _this.diaryOperationClose();
  },

  /**
   * 关闭隐私弹窗
   */
  diaryPrivacyClose: function () {
    var _this = this;
    _this.setData({
      diaryPrivacyShow: false
    })
  },

  /**
   * 修改日记隐私
   */
  updateDiaryPrivate: function (e) {
    var _this = this;
    var isprivate = e.currentTarget.dataset.isprivate;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.diaryid = _this.data.diaryid;
        data.isprivate = isprivate;
        util.post(api.Home_UpdateDiaryPrivateApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.diaryPrivacyClose();
            _this.getDiaryInfoByDiaryId();
            util.dialogAlert("修改成功");
          }
        });
      })
    }
  },

  /**
   * 点赞的人弹窗
   */
  giveLikeUserDialogShow: function () {
    var _this = this;
    _this.setData({
      giveLikeUserDialogShow: !_this.data.giveLikeUserDialogShow
    })
  },

  /**
   * 修改日记的浏览次数
   */
  updateDiaryPreviewCount: function () {
    var _this = this;
    var data = { "ordDiaryid": _this.data.diaryid };
    util.post(api.Home_UpdateDiaryPreviewCountUrl, data).then(function (res) {
    });
  },

  /**
   * 语音拒绝授权的提示弹窗关闭
   */
  audioOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      audioOauhRefusedDialogShow: false
    })
  },

  /**
   * 语音拒绝授权的提示弹窗确认动作
   */
  audioOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.record"] == true) {
          // 授权成功
          _this.audioOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.audioOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * 能量卡片展开
   */
  energyCardDialogShow: function(){
    var _this = this;
    var energyCardDialog = _this.data.energyCardDialog;
    energyCardDialog.show = true;
    _this.setData({
      energyCardDialog: energyCardDialog
    })
  },

  /**
   * 能量卡片关闭
   */
  energyCardDialogClose: function(){
    var _this = this;
    var energyCardDialog = { "show": false };
    _this.setData({
      energyCardDialog: energyCardDialog
    })
  },

  /**
   * 成长：打开弹窗
   */
  seedDialogShow: function (e) {
    var _this = this;
    var seedDialog = _this.data.seedDialog;
    seedDialog.show = true;
    seedDialog.diaryInfo = _this.data.diaryInfo;
    _this.setData({
      seedDialog: seedDialog
    })
  },

  /**
   * 成长：关闭弹窗
   */
  seedDialogClose: function () {
    var _this = this;
    var seedDialog = { "show": false, "seedRulesDialogShow": false, "diaryInfo": {} };
    _this.setData({
      seedDialog: seedDialog
    })
  },

  /**
   * 种子法则
   */
  seedRulesDialogShow: function () {
    var _this = this;
    _this.setData({
      ["seedDialog.seedRulesDialogShow"]: !_this.data.seedDialog.seedRulesDialogShow
    })
  }
})